package com.baf.xbmcapi;

import java.io.InputStream;
import android.util.Log;
import java.io.OutputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.json.JSONException;
import org.json.JSONObject;

public class XBMCInterface {
	
	static String ipAddress;
	static int port;
	public static void setIpAddress(String ia)
	{
		ipAddress=ia;
	}
	public static void setPort(int prt)
	{
		port=prt;
	}
	public static String sendMessage(String message) throws Exception
	{
			Log.v("XBMCInterface", "Hello World" );
			InetAddress lh = InetAddress.getByName(ipAddress);
			//System.out.println( lh);
			Socket s = new Socket ();
//			s.bind(new InetSocketAddress(10993));
			s.connect(new InetSocketAddress(lh,port));

		OutputStream os = s.getOutputStream();
		InputStream is = s.getInputStream();
		//os.write("{\"jsonrpc\": \"2.0\", \"method\": \"XBMC.SetVolume\", \"params\" : 70 , \"id\": 1}".getBytes());
		os.write(message.getBytes());
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[] barr = new byte[1024];
		int jkl ;
		Thread.sleep(100);
		int available = bis.available();
		StringBuffer output = new StringBuffer();
		System.out.println(" Available is "+available);
		while ( ( available > 0 ) && (jkl = bis.read(barr)) != -1 )
		{
			available = bis.available();
			output.append(new String(barr));
			barr = new byte[1024] ;
		}
		bis.close();
		is.close();
		os.flush();
		os.close();
		s.close();
		return new String(output);
		
	}
	
	public static void increaseVolume(int increment) throws Exception
	{
		
		JSONObject incvolobj = new JSONObject();
		incvolobj.put("jsonrpc","2.0");
		incvolobj.put("method","XBMC.SetVolume");
		incvolobj.put("id","1321");
		incvolobj.put("params", getVolume() + increment);
		sendMessage(incvolobj.toString());
	}
	public static void decreaseVolume(int decrement) throws Exception
	{
		JSONObject incvolobj = new JSONObject();
		incvolobj.put("jsonrpc","2.0");
		incvolobj.put("method","XBMC.SetVolume");
		incvolobj.put("id","1326");
		incvolobj.put("params", getVolume() - decrement);
		sendMessage(incvolobj.toString());
	}
	
	public static int getVolume() throws Exception
	{
		JSONObject getvolobj = new JSONObject();
		getvolobj.put("jsonrpc","2.0");
		getvolobj.put("method","XBMC.GetVolume");
		getvolobj.put("id","1320");
		
		String response = sendMessage(getvolobj.toString());
		JSONObject jo = new JSONObject(response);
		int curvol = jo.getInt("result");
		return curvol ;
	}
}
